﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

using Bricks.Component.Utils;
using Bricks.Business.Models;
using Bricks.Business.Models.FlowProcess;
using Bricks.Site.Models;
using Bricks.Business.Data.Repositories.ScheduleManagement;
using System.Xml;
using Bricks.Business.Service;
using Bricks.Business.Models.ScheduleManagement;
using System.Globalization;
using Bricks.Business.Data.Repositories.FlowProcess;


namespace ChiDao.Business.Service.Impl
{
    [Export(typeof(ITotalMaintenanceService))]
    internal class TotalMaintenanceService : ITotalMaintenanceService
    {
        #region 属性
        [Import]
        protected IStatisticsItemMaintenanceRepository StatisticsItemMaintenanceRepository { get; set; }
        [Import]
        protected ITotalMaintenanceRepository TotalMaintenanceRepository { get; set; }
        [Import]
        protected ITotalMaintenanceDetailsRepository TotalMaintenanceDetailsRepository { get; set; }
        [Import]
        protected ITotalReviseRepository TotalReviseRepository { get; set; }
        [Import]
        protected ITotalReviseDetailsRepository TotalReviseDetailsRepository { get; set; }
        [Import]
        protected IBaklogTaskRepository BaklogTaskRepository { get; set; }
        #endregion

        public IQueryable<TotalMaintenance> TotalMaintenances
        {
            get { return TotalMaintenanceRepository.Entities; }
        }

        #region 主界面加载
        //获取修订记录
        public List<TotalMaintenanceView> GetTotalReviseList(Guid projectID, string contractType, Guid contractID)
        {
            List<TotalMaintenanceView> lstTotalMaintenanceView = new List<TotalMaintenanceView>();
            var queryTotalRevise = from t in TotalReviseRepository.Entities
                                   where t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID
                                   orderby t.ReviseDate descending
                                   select t;
            lstTotalMaintenanceView.Add(new TotalMaintenanceView() { TotalReviseID = Guid.Empty, ReviseDisplay = "流程数据" });
            foreach (var item in queryTotalRevise)
            {
                lstTotalMaintenanceView.Add(new TotalMaintenanceView() { TotalReviseID = item.ID, ReviseDisplay = "第" + item.ReviseNum.ToString() + "次" + item.ReviseDate.ToString("yyyy年MM月dd日", DateTimeFormatInfo.InvariantInfo) + ",总金额" + item.ReviseMoney + "万元" });
            }
            return lstTotalMaintenanceView;
        }

        //获取总量维护明细
        public List<TotalMaintenanceDetailsView> GetTotalMaintenanceDetailList(Guid projectID, string contractType, Guid contractID)
        {
            var queryTotalMaintenanceDetail = from t in TotalMaintenanceRepository.Entities
                                              join td in TotalMaintenanceDetailsRepository.Entities
                                              on t.ID equals td.TotalMaintenanceID
                                              where t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID
                                              select td;
            var queryData = from s in StatisticsItemMaintenanceRepository.Entities
                            join t in queryTotalMaintenanceDetail
                            on s.ID equals t.StatisticsItemID into joinedEmpT
                            from tempT in joinedEmpT.DefaultIfEmpty()
                            where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                            orderby s.OrderNo
                            select new
                            {
                                StatisticsItemID = s.ID,
                                s.StatisticsItemName,
                                s.PID,
                                s.EngineeringUnit,
                                s.MoneyUnit,
                                ID = tempT == null ? Guid.NewGuid() : tempT.ID,
                                TotalMaintenanceID = tempT == null ? Guid.NewGuid() : tempT.TotalMaintenanceID,
                                tempT.EngineeringNum,
                                tempT.MoneyNum
                            };

            List<TotalMaintenanceDetailsView> lstTotalMaintenanceDetailsView = new List<TotalMaintenanceDetailsView>();
            foreach (var item in queryData)
            {
                string parentStatisticsItemName = item.StatisticsItemName;
                if (item.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                }
                if (!string.IsNullOrEmpty(item.EngineeringUnit))
                {
                    TotalMaintenanceDetailsView totalMaintenanceDetailsView = new TotalMaintenanceDetailsView();
                    totalMaintenanceDetailsView.ID = item.ID;
                    totalMaintenanceDetailsView.StatisticsItemID = item.StatisticsItemID;
                    totalMaintenanceDetailsView.StatisticsItemName = item.StatisticsItemName;
                    totalMaintenanceDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    totalMaintenanceDetailsView.Unit = item.EngineeringUnit;
                    totalMaintenanceDetailsView.Amount = item.EngineeringNum;
                    totalMaintenanceDetailsView.IsBelongToMoneyNum = "0";

                    lstTotalMaintenanceDetailsView.Add(totalMaintenanceDetailsView);
                }
                if (!string.IsNullOrEmpty(item.MoneyUnit))
                {
                    TotalMaintenanceDetailsView totalMaintenanceDetailsView = new TotalMaintenanceDetailsView();
                    totalMaintenanceDetailsView.ID = item.ID;
                    totalMaintenanceDetailsView.StatisticsItemID = item.StatisticsItemID;
                    totalMaintenanceDetailsView.StatisticsItemName = item.StatisticsItemName;
                    totalMaintenanceDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    totalMaintenanceDetailsView.Unit = item.MoneyUnit;
                    totalMaintenanceDetailsView.Amount = item.MoneyNum;
                    totalMaintenanceDetailsView.IsBelongToMoneyNum = "1";

                    lstTotalMaintenanceDetailsView.Add(totalMaintenanceDetailsView);
                }
            }
            return lstTotalMaintenanceDetailsView;
        }

        private string GetParentStatisticsItemName(Guid? PID)
        {
            string parentStatisticsItemName = string.Empty;
            StatisticsItemMaintenance parentStatisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.SingleOrDefault(s => s.ID == PID);
            if (parentStatisticsItemMaintenance != null)
            {
                parentStatisticsItemName = parentStatisticsItemMaintenance.StatisticsItemName;
            }
            return parentStatisticsItemName;
        }

        //获取修订明细
        public List<TotalMaintenanceDetailsView> GetTotalReviseDetailList(Guid projectID, string contractType, Guid totalReviseID)
        {
            var queryTotalReviseDetails = from td in TotalReviseDetailsRepository.Entities
                                          where td.TotalReviseID == totalReviseID
                                          select td;
            var queryData = from s in StatisticsItemMaintenanceRepository.Entities
                            join t in queryTotalReviseDetails
                            on s.ID equals t.StatisticsItemID into joinedEmpT
                            from tempT in joinedEmpT.DefaultIfEmpty()
                            where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                            orderby s.OrderNo
                            select new
                            {
                                StatisticsItemID = s.ID,
                                s.StatisticsItemName,
                                s.PID,
                                s.EngineeringUnit,
                                s.MoneyUnit,
                                ID = tempT == null ? Guid.NewGuid() : tempT.ID,
                                ReviseID = tempT == null ? Guid.NewGuid() : tempT.TotalReviseID,
                                tempT.EngineeringNum,
                                tempT.MoneyNum
                            };

            List<TotalMaintenanceDetailsView> lstTotalMaintenanceDetailsView = new List<TotalMaintenanceDetailsView>();
            foreach (var item in queryData)
            {
                string parentStatisticsItemName = item.StatisticsItemName;
                if (item.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                }
                if (!string.IsNullOrEmpty(item.EngineeringUnit))
                {
                    TotalMaintenanceDetailsView totalMaintenanceDetailsView = new TotalMaintenanceDetailsView();
                    totalMaintenanceDetailsView.ID = item.ID;
                    totalMaintenanceDetailsView.StatisticsItemName = item.StatisticsItemName;
                    totalMaintenanceDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    totalMaintenanceDetailsView.Unit = item.EngineeringUnit;
                    totalMaintenanceDetailsView.Amount = item.EngineeringNum;

                    lstTotalMaintenanceDetailsView.Add(totalMaintenanceDetailsView);
                }
                if (!string.IsNullOrEmpty(item.MoneyUnit))
                {
                    TotalMaintenanceDetailsView totalMaintenanceDetailsView = new TotalMaintenanceDetailsView();
                    totalMaintenanceDetailsView.ID = item.ID;
                    totalMaintenanceDetailsView.StatisticsItemName = item.StatisticsItemName;
                    totalMaintenanceDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    totalMaintenanceDetailsView.Unit = item.MoneyUnit;
                    totalMaintenanceDetailsView.Amount = item.MoneyNum;

                    lstTotalMaintenanceDetailsView.Add(totalMaintenanceDetailsView);
                }
            }
            return lstTotalMaintenanceDetailsView;
        }

        //获取多标段修订明细汇总
        public List<TotalMaintenanceDetailsView> GetTotalReviseDetailListForPreview(Guid projectID, string contractType, List<Guid> lstContractID)
        {
            Dictionary<Guid, TotalReviseDetails> dicTotalReviseDetails = new Dictionary<Guid, TotalReviseDetails>();
            foreach (Guid contractID in lstContractID)
            {
                TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
                if (totalRevise != null)
                {
                    var queryTotalReviseDetails = from td in TotalReviseDetailsRepository.Entities
                                                  where td.TotalReviseID == totalRevise.ID
                                                  select td;
                    foreach (var item in queryTotalReviseDetails)
                    {
                        if (dicTotalReviseDetails.ContainsKey(item.StatisticsItemID))
                        {
                            StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == item.StatisticsItemID);

                            #region 统计EngineeringNum
                            if (!string.IsNullOrEmpty(statisticsItemMaintenance.EngineeringUnit) && !string.IsNullOrEmpty(item.EngineeringNum))
                            {
                                if (!string.IsNullOrEmpty(dicTotalReviseDetails[item.StatisticsItemID].EngineeringNum))
                                {
                                    if (statisticsItemMaintenance.EngineeringUnit.Contains('/'))
                                    {
                                        string[] totalEngineeringNum = dicTotalReviseDetails[item.StatisticsItemID].EngineeringNum.Split('/');
                                        string[] engineeringNum = item.EngineeringNum.Split('/');
                                        if (engineeringNum.Length == 1)
                                        {
                                            if (totalEngineeringNum.Length == 1)
                                            {
                                                dicTotalReviseDetails[item.StatisticsItemID].EngineeringNum = (Convert.ToDecimal(totalEngineeringNum[0]) + Convert.ToDecimal(engineeringNum[0])).ToString();
                                            }
                                            else if (totalEngineeringNum.Length == 2)
                                            {
                                                dicTotalReviseDetails[item.StatisticsItemID].EngineeringNum = (Convert.ToDecimal(totalEngineeringNum[0]) + Convert.ToDecimal(engineeringNum[0])).ToString() + "/" + totalEngineeringNum[1];
                                            }
                                        }
                                        else if (engineeringNum.Length == 2)
                                        {
                                            if (totalEngineeringNum.Length == 1)
                                            {
                                                dicTotalReviseDetails[item.StatisticsItemID].EngineeringNum = (Convert.ToDecimal(totalEngineeringNum[0]) + Convert.ToDecimal(engineeringNum[0])).ToString() + "/" + engineeringNum[1];
                                            }
                                            else
                                            {
                                                dicTotalReviseDetails[item.StatisticsItemID].EngineeringNum = (Convert.ToDecimal(totalEngineeringNum[0]) + Convert.ToDecimal(engineeringNum[0])).ToString() + "/" + (Convert.ToDecimal(totalEngineeringNum[1]) + Convert.ToDecimal(engineeringNum[1])).ToString();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        decimal total = Convert.ToDecimal(dicTotalReviseDetails[item.StatisticsItemID].EngineeringNum);
                                        decimal itemValue = Convert.ToDecimal(item.EngineeringNum);
                                        dicTotalReviseDetails[item.StatisticsItemID].EngineeringNum = (total + itemValue).ToString();
                                    }
                                }
                                else
                                {
                                    dicTotalReviseDetails[item.StatisticsItemID].EngineeringNum = item.EngineeringNum;
                                }
                            }
                            #endregion

                            //统计MoneyNum
                            if (!string.IsNullOrEmpty(statisticsItemMaintenance.MoneyUnit) && !string.IsNullOrEmpty(item.MoneyNum))
                            {
                                decimal total = string.IsNullOrEmpty(dicTotalReviseDetails[item.StatisticsItemID].MoneyNum) ? 0 : Convert.ToDecimal(dicTotalReviseDetails[item.StatisticsItemID].MoneyNum);
                                decimal itemValue = Convert.ToDecimal(item.MoneyNum);
                                dicTotalReviseDetails[item.StatisticsItemID].MoneyNum = (total + itemValue).ToString();
                            }
                        }
                        else
                        {
                            dicTotalReviseDetails.Add(item.StatisticsItemID, item);
                        }
                    }
                }
            }

            List<TotalReviseDetails> lstTotalReviseDetails = new List<TotalReviseDetails>();
            foreach (KeyValuePair<Guid, TotalReviseDetails> KeyValuePair in dicTotalReviseDetails)
            {
                lstTotalReviseDetails.Add(KeyValuePair.Value);
            }

            var queryData = from s in StatisticsItemMaintenanceRepository.Entities.ToList()
                            join t in lstTotalReviseDetails
                            on s.ID equals t.StatisticsItemID into joinedEmpT
                            from tempT in joinedEmpT.DefaultIfEmpty()
                            where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                            orderby s.OrderNo
                            select new
                            {
                                StatisticsItemID = s.ID,
                                s.StatisticsItemName,
                                s.PID,
                                s.EngineeringUnit,
                                s.MoneyUnit,
                                ID = tempT == null ? Guid.NewGuid() : tempT.ID,
                                EngineeringNum = tempT == null ? string.Empty : tempT.EngineeringNum,
                                MoneyNum = tempT == null ? string.Empty : tempT.MoneyNum
                            };

            List<TotalMaintenanceDetailsView> lstTotalMaintenanceDetailsView = new List<TotalMaintenanceDetailsView>();
            foreach (var item in queryData)
            {
                string parentStatisticsItemName = item.StatisticsItemName;
                if (item.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                }
                if (!string.IsNullOrEmpty(item.EngineeringUnit))
                {
                    TotalMaintenanceDetailsView totalMaintenanceDetailsView = new TotalMaintenanceDetailsView();
                    totalMaintenanceDetailsView.ID = item.ID;
                    totalMaintenanceDetailsView.StatisticsItemName = item.StatisticsItemName;
                    totalMaintenanceDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    totalMaintenanceDetailsView.Unit = item.EngineeringUnit;
                    totalMaintenanceDetailsView.Amount = item.EngineeringNum;

                    lstTotalMaintenanceDetailsView.Add(totalMaintenanceDetailsView);
                }
                if (!string.IsNullOrEmpty(item.MoneyUnit))
                {
                    TotalMaintenanceDetailsView totalMaintenanceDetailsView = new TotalMaintenanceDetailsView();
                    totalMaintenanceDetailsView.ID = item.ID;
                    totalMaintenanceDetailsView.StatisticsItemName = item.StatisticsItemName;
                    totalMaintenanceDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    totalMaintenanceDetailsView.Unit = item.MoneyUnit;
                    totalMaintenanceDetailsView.Amount = item.MoneyNum;

                    lstTotalMaintenanceDetailsView.Add(totalMaintenanceDetailsView);
                }
            }
            return lstTotalMaintenanceDetailsView;
        }
        #endregion

        //获取总量维护记录
        public TotalMaintenanceView GetTotalMaintenanceByID(Guid id)
        {
            TotalMaintenance totalMaintenance = TotalMaintenanceRepository.Entities.SingleOrDefault(t => t.ID == id);
            TotalMaintenanceView totalMaintenanceView = null;
            if (totalMaintenance != null)
            {
                totalMaintenanceView = new TotalMaintenanceView();
                totalMaintenanceView.ID = totalMaintenance.ID;
                totalMaintenanceView.FlowCode = totalMaintenance.FlowCode;
                totalMaintenanceView.ProjectID = totalMaintenance.ProjectID;
                totalMaintenanceView.ContractType = totalMaintenance.ContractType;
                totalMaintenanceView.ContractID = totalMaintenance.ContractID;
                totalMaintenanceView.RequestDate = totalMaintenance.RequestDate;
                totalMaintenanceView.RequestNodeCode = totalMaintenance.RequestNodeCode;
                totalMaintenanceView.RequestUserDepartment = totalMaintenance.RequestUserDepartment;
                totalMaintenanceView.RequestPerson = totalMaintenance.RequestPerson;
                totalMaintenanceView.HandleState = totalMaintenance.HandleState;
                totalMaintenanceView.AssociatedNodeCode = totalMaintenance.AssociatedNodeCode;
                totalMaintenanceView.LastUpdateUserDepartment = totalMaintenance.LastUpdateUserDepartment;
                totalMaintenanceView.LastUpdateUser = totalMaintenance.LastUpdateUser;
                totalMaintenanceView.LastUpdateTime = totalMaintenance.LastUpdateTime;
                totalMaintenanceView.SaveState = totalMaintenance.SaveState;
            }
            return totalMaintenanceView;
        }

        #region 单据保存
        public void SaveTotalMaintenance(TotalMaintenanceView totalMaintenanceView, List<TotalMaintenanceDetailsView> saveList, bool isUpdateDetails = true)
        {
            TotalMaintenance record = TotalMaintenanceRepository.Entities.FirstOrDefault(a => a.ID == totalMaintenanceView.ID);
            if (record != null)
            {
                UpdateTotalMaintenance(record, totalMaintenanceView);
            }
            else
            {
                InsertTotalMaintenance(totalMaintenanceView);
            }

            if (isUpdateDetails)
            {
                DeleteTotalMaintenanceDetails(totalMaintenanceView);
                foreach (TotalMaintenanceDetailsView totalMaintenanceDetailsView in saveList)
                {
                    InsertTotalMaintenanceDetails(totalMaintenanceDetailsView);
                }
            }
        }

        private void InsertTotalMaintenance(TotalMaintenanceView totalMaintenanceView)
        {
            TotalMaintenance record = new TotalMaintenance()
            {
                ID = totalMaintenanceView.ID,
                FlowCode = totalMaintenanceView.FlowCode,
                ProjectID = totalMaintenanceView.ProjectID,
                ContractType = totalMaintenanceView.ContractType,
                ContractID = totalMaintenanceView.ContractID,
                RequestDate = totalMaintenanceView.RequestDate,
                RequestNodeCode = totalMaintenanceView.RequestNodeCode,
                RequestUserDepartment = totalMaintenanceView.RequestUserDepartment,
                RequestPerson = totalMaintenanceView.RequestPerson,
                HandleState = totalMaintenanceView.HandleState,
                AssociatedNodeCode = totalMaintenanceView.AssociatedNodeCode,
                LastUpdateUserDepartment = totalMaintenanceView.LastUpdateUserDepartment,
                LastUpdateUser = totalMaintenanceView.LastUpdateUser,
                LastUpdateTime = totalMaintenanceView.LastUpdateTime,
                SaveState = totalMaintenanceView.SaveState
            };
            TotalMaintenanceRepository.Insert(record);
        }

        private void UpdateTotalMaintenance(TotalMaintenance record, TotalMaintenanceView totalMaintenanceView)
        {
            record.HandleState = totalMaintenanceView.HandleState;
            record.AssociatedNodeCode = totalMaintenanceView.AssociatedNodeCode;
            record.LastUpdateUserDepartment = totalMaintenanceView.LastUpdateUserDepartment;
            record.LastUpdateUser = totalMaintenanceView.LastUpdateUser;
            record.LastUpdateTime = totalMaintenanceView.LastUpdateTime;
            record.SaveState = totalMaintenanceView.SaveState;
            TotalMaintenanceRepository.Update(record);
        }

        private void DeleteTotalMaintenanceDetails(TotalMaintenanceView totalMaintenanceView)
        {
            IQueryable<TotalMaintenanceDetails> lstTotalMaintenanceDetail = TotalMaintenanceDetailsRepository.Entities.Where(a => a.TotalMaintenanceID == totalMaintenanceView.ID);
            List<Guid> lstDeleteID = new List<Guid>();
            foreach (TotalMaintenanceDetails totalMaintenanceDetails in lstTotalMaintenanceDetail)
            {
                lstDeleteID.Add(totalMaintenanceDetails.ID);
            }
            foreach (Guid id in lstDeleteID)
            {
                TotalMaintenanceDetailsRepository.Delete(id);
            }
        }

        private void InsertTotalMaintenanceDetails(TotalMaintenanceDetailsView totalMaintenanceDetailsView)
        {
            TotalMaintenanceDetails record = new TotalMaintenanceDetails()
            {
                ID = totalMaintenanceDetailsView.ID,
                TotalMaintenanceID = totalMaintenanceDetailsView.TotalMaintenanceID,
                StatisticsItemID = totalMaintenanceDetailsView.StatisticsItemID,
                EngineeringNum = totalMaintenanceDetailsView.EngineeringNum,
                MoneyNum = totalMaintenanceDetailsView.MoneyNum
            };
            TotalMaintenanceDetailsRepository.Insert(record);
        }
        #endregion

        public OperationResult Revise(Guid projectID, string contractType, Guid contractID, Guid totalReviseID)
        {
            try
            {
                TotalMaintenance record = TotalMaintenanceRepository.Entities.SingleOrDefault(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID);
                TotalRevise recordRevise = TotalReviseRepository.Entities.SingleOrDefault(t => t.ID == totalReviseID);
                if (record != null && recordRevise != null)
                {
                    record.HandleState = "0";
                    record.AssociatedNodeCode = record.RequestNodeCode;
                    record.LastUpdateUserDepartment = record.RequestUserDepartment;
                    record.LastUpdateUser = record.RequestPerson;
                    TotalMaintenanceRepository.Update(record);

                    List<TotalMaintenanceDetails> lstTotalMaintenanceDetail = TotalMaintenanceDetailsRepository.Entities.Where(a => a.TotalMaintenanceID == record.ID).ToList();
                    foreach (TotalMaintenanceDetails totalMaintenanceDetails in lstTotalMaintenanceDetail)
                    {
                        TotalMaintenanceDetailsRepository.Delete(totalMaintenanceDetails.ID);
                    }

                    List<TotalReviseDetails> lstTotalReviseDetail = TotalReviseDetailsRepository.Entities.Where(a => a.TotalReviseID == recordRevise.ID).ToList();
                    foreach (TotalReviseDetails totalReviseDetails in lstTotalReviseDetail)
                    {
                        TotalMaintenanceDetails totalMaintenanceDetails = new TotalMaintenanceDetails();
                        totalMaintenanceDetails.TotalMaintenanceID = record.ID;
                        totalMaintenanceDetails.StatisticsItemID = totalReviseDetails.StatisticsItemID;
                        totalMaintenanceDetails.EngineeringNum = totalReviseDetails.EngineeringNum;
                        totalMaintenanceDetails.MoneyNum = totalReviseDetails.MoneyNum;
                        TotalMaintenanceDetailsRepository.Insert(totalMaintenanceDetails);
                    }

                    string sql = @"DELETE FROM BaklogTasks WHERE RecordID='" + record.ID + "';" +
                                  "DELETE FROM BaklogTaskTemps WHERE RecordID='" + record.ID + "';" +
                                  "DELETE FROM CompleteFlowNodes WHERE RecordID='" + record.ID + "';" +
                                  "DELETE FROM FlowGraphNodes WHERE RecordID='" + record.ID + "';" +
                                  "DELETE FROM FlowProcessMessages WHERE RecordID='" + record.ID + "';" +
                                  "DELETE FROM ProcessedTasks WHERE RecordID='" + record.ID + "';";
                    TotalMaintenanceRepository.ExeSqlCommon(sql);

                    BaklogTask baklogTask = new BaklogTask();
                    baklogTask.ID = GuidHelper.NewGuid();
                    baklogTask.RecordID = record.ID.ToString();
                    baklogTask.TaskType = record.FlowCode;
                    baklogTask.RequestDate = record.RequestDate;
                    baklogTask.CurrentFlowNodeCode = record.AssociatedNodeCode;
                    baklogTask.CurrentProcessPersonDepartment = record.LastUpdateUserDepartment;
                    baklogTask.CurrentProcessPerson = record.LastUpdateUser;
                    baklogTask.NodeLevel = 1;
                    BaklogTaskRepository.Insert(baklogTask);

                    return new OperationResult(OperationResultType.Success, "修订成功", record);
                }
                else
                {
                    return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");
                }
            }
            catch (Exception ex)
            {
                return new OperationResult(OperationResultType.Error, "删除失败:" + ex.Message);
            }
        }

        public OperationResult Delete(Guid projectID, string contractType, Guid contractID)
        {
            try
            {
                TotalMaintenance record = TotalMaintenanceRepository.Entities.SingleOrDefault(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID);
                if (record == null)
                    return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");
                if (record != null)
                {
                    TotalMaintenanceRepository.Delete(record);
                }

                List<TotalRevise> lstTotalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).ToList();
                foreach (TotalRevise totalRevise in lstTotalRevise)
                {
                    List<TotalReviseDetails> lstTotalReviseDetails = TotalReviseDetailsRepository.Entities.Where(t => t.TotalReviseID == totalRevise.ID).ToList();
                    foreach (TotalReviseDetails totalReviseDetails in lstTotalReviseDetails)
                    {
                        TotalReviseDetailsRepository.Delete(totalReviseDetails.ID);
                    }
                    TotalReviseRepository.Delete(totalRevise.ID);
                }
                string sql = @"DELETE FROM TotalMaintenanceDetails WHERE TotalMaintenanceID='" + record.ID + "';" +
                              "DELETE FROM BaklogTasks WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM BaklogTaskTemps WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM CompleteFlowNodes WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM FlowGraphNodes WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM FlowProcessMessages WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM ProcessedTasks WHERE RecordID='" + record.ID + "';";
                TotalMaintenanceRepository.ExeSqlCommon(sql);
                return new OperationResult(OperationResultType.Success, "删除成功", record);
            }
            catch (Exception ex)
            {
                return new OperationResult(OperationResultType.Error, "删除失败:" + ex.Message);
            }
        }

        public void AddReviseData(Guid totalMaintenanceID)
        {
            TotalMaintenance totalMaintenance = TotalMaintenanceRepository.Entities.SingleOrDefault(t => t.ID == totalMaintenanceID);
            if (totalMaintenance != null)
            {
                TotalRevise totalRevise = new TotalRevise();
                decimal totalMoney = 0;
                List<TotalMaintenanceDetails> lstTotalMaintenanceDetail = TotalMaintenanceDetailsRepository.Entities.Where(td => td.TotalMaintenanceID == totalMaintenanceID).ToList();
                foreach (TotalMaintenanceDetails totalMaintenanceDetails in lstTotalMaintenanceDetail)
                {
                    StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == totalMaintenanceDetails.StatisticsItemID);

                    //统计MoneyNum
                    if (statisticsItemMaintenance != null && !string.IsNullOrEmpty(totalMaintenanceDetails.MoneyNum))
                    {
                        if (statisticsItemMaintenance.MoneyUnit == "万元")
                        {
                            totalMoney = totalMoney + Convert.ToDecimal(totalMaintenanceDetails.MoneyNum);
                        }
                        else
                        {
                            totalMoney = totalMoney + Convert.ToDecimal(totalMaintenanceDetails.MoneyNum) / 10000;
                        }
                    }

                    TotalReviseDetails totalReviseDetails = new TotalReviseDetails();
                    totalReviseDetails.TotalReviseID = totalRevise.ID;
                    totalReviseDetails.StatisticsItemID = totalMaintenanceDetails.StatisticsItemID;
                    totalReviseDetails.EngineeringNum = totalMaintenanceDetails.EngineeringNum;
                    totalReviseDetails.MoneyNum = totalMaintenanceDetails.MoneyNum;
                    TotalReviseDetailsRepository.Insert(totalReviseDetails);
                }

                totalRevise.ProjectID = totalMaintenance.ProjectID;
                totalRevise.ContractType = totalMaintenance.ContractType;
                totalRevise.ContractID = totalMaintenance.ContractID;
                totalRevise.ReviseNum = GetNextOrderNo(totalMaintenance);
                totalRevise.ReviseDate = DateTime.Now;
                totalRevise.ReviseMoney = totalMoney.ToString();
                TotalReviseRepository.Insert(totalRevise);
            }
        }

        private int GetNextOrderNo(TotalMaintenance totalMaintenance)
        {
            int num = 1;
            IQueryable<TotalRevise> lstTotalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == totalMaintenance.ProjectID && t.ContractType == totalMaintenance.ContractType && t.ContractID == totalMaintenance.ContractID);
            if (lstTotalRevise.Count() > 0)
            {
                object max = lstTotalRevise.Max(t => t.ReviseNum);

                if (max != null)
                {
                    num = Convert.ToInt32(max) + 1;
                }
            }
            return num;
        }
    }
}